package com.wframe.project.former.dataservices.marketing;

import com.frame.database.JBaseDao;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.util.DateConvert;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/6/12.
 */
public class BuyDao extends JBaseDao {
    public BuyDao(){
        super("wb_promotion_buy_send");
    }
    public PageResult querybuyList(JdataBean parms, int size, int pageno) throws Exception{
        String sql="select b.id,b.promotionid,(select t.`name` from wb_products t where p.product_val=t.id) productname,p.sort_value,p.platform,(select (ifnull(pr.amount,0)-ifnull(pr.djamount,0)) from wb_products_prices pr where pr.id=p.product_val) productamount,p.start_time,p.end_time,p.state,p.time,p.name promotionsname,p.remark,p.product_val,p.description,UNIX_TIMESTAMP(p.start_time) startmsec,UNIX_TIMESTAMP(p.end_time) endmsec,UNIX_TIMESTAMP() newtime from wb_promotion_buy_send b,wb_promotions p where b.promotionid=p.id and p.promotion_type=1 and (state=1 or state=0)";
        List parmlist = new ArrayList();
        if (parms != null){
            if (StringUtils.isNotBlank(parms.getString("name"))) {
                sql += " and p.name like ?";
                parmlist.add("%" + parms.getString("name") + "%");
            }
            if (StringUtils.isNotBlank(parms.getString("platform"))) {
                sql += " and p.platform=?";
                parmlist.add(parms.getString("platform"));
            }
            if (StringUtils.isNotBlank(parms.getString("start"))) {
                sql += " and p.start_time>=?";
                parmlist.add(DateConvert.toDate(parms.getString("start")+" 00:00:00"));
            }
            if (StringUtils.isNotBlank(parms.getString("end"))) {
                sql += " and p.start_time<=?";
                parmlist.add(DateConvert.toDate(parms.getString("end")+" 23:59:59"));
            }
            //已暂停
            if (StringUtils.isNotBlank(parms.getString("state")) && parms.getString("state").equals("0")){
                sql +=" and state=0 and start_time<now() and end_time>NOW()";
            }
            //未开始
            if (StringUtils.isNotBlank(parms.getString("state")) && parms.getString("state").equals("1")){
                sql +=" and state=1 and start_time>now()";
            }
            //进行中
            if (StringUtils.isNotBlank(parms.getString("state")) && parms.getString("state").equals("2")){
                sql +=" and state =1 AND start_time<now() and end_time>NOW() ";
            }
            //已失效
            if (StringUtils.isNotBlank(parms.getString("state")) && parms.getString("state").equals("3")){
                sql +=" and (state = 1 or state = 0 )and  end_time<NOW()";
            }
        }
        sql += " order by p.sort_value desc,b.id desc";
        return getSession().query2(sql, parmlist, size, pageno);
    }
}
